/*
    This file is part of p4f
    Copyright (C) 2009  Sebastian Fernandez

    p4f is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as 
    published by the Free Software Foundation, either version 3 of the 
    License, or (at your option) any later version.

    p4f is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

#include <thread.h>

Thread::Thread()
{
	
}

void Thread::start()
{
#ifdef _WIN32
	hThreadArray = CreateThread(
			NULL,				// default security attributes
			0,					// use default stack size
			thread_proxy,		// thread function name
			this,				// argument to thread function
			0,					// use default creation flags
			&dwThreadIdArray);	// returns the thread identifier
	/*
	if(hThreadArray==NULL)
		ops_error("Cannot create thread");
	return 0;
	*/
#else
	/*
	if(pthread_create(&threads,NULL,function,(void *)args)) //create the thread
		ops_error("Cannot create thread");
	*/
	pthread_create(&threads,NULL,thread_proxy,(void *)this);
#endif
	return;
}

Thread::~Thread()
{
#ifdef _WIN32
	CloseHandle (hThreadArray);
#endif
}

#ifdef _WIN32
DWORD _stdcall thread_proxy(void *t)
#else
void *thread_proxy(void *t)
#endif
{
	Thread *m = (Thread *)t;
	m->run((void *)t);
	return NULL;
}

/*
 * This function will block the calling process, use careful or can
 * produce forever block
 */
void Thread::wait()
{
#ifdef _WIN32
	WaitForSingleObject(hThreadArray, INFINITE);
#else
	pthread_join(threads, NULL);
#endif
}

void Thread::kill()
{
#ifdef _WIN32
	TerminateThread(hThreadArray,1);
#else
	//pthread_cancel(threads);
	pthread_kill(threads, NULL);
#endif
}
